package com.lib.base.utils.thread;

import android.os.Handler;

import com.lib.base.utils.log.LogHelper;

/**
 * 定时任务
 */
public class TimingThread extends Thread {

    private boolean run;
    private Handler mHandler;
    private int period = 1000;//默认 1 秒一次

    private ITimingThreadListener mListener;
    public void setLoadListener(ITimingThreadListener listener) {
        this.mListener = listener;
    }

    /**
     * 设置线程的执行间隔时间
     * @param delayMillis : 默认500毫秒一次
     */
    public void setThreadDelayMillis(int delayMillis) {
        this.period = delayMillis;
    }

    /**
     * 启动线程
     */
    public void startThread() {
        if (run){
            LogHelper.e("The current task is not completed");
            return;
        }
        LogHelper.e("Task Started");
        mHandler = new Handler();
        mHandler.postDelayed(mRunable, period);
        run = true;
    }

    /**
     * 停止线程
     */
    public void stopThread() {
        if (mHandler == null) {
            return;
        }
        LogHelper.e("Task Closed");
        run = false;
        mHandler.removeCallbacks(mRunable);
    }
    /**
     * 获取的线程
     */
    Runnable mRunable = new Runnable() {
        @Override
        public void run() {
            if (!run) {
                stopThread();
                return;
            }
            if (mListener != null){
                mListener.onLoading();
            }
            mHandler.postDelayed(mRunable, period);
        }
    };

    /* 用于线程启动回调 */
    public interface ITimingThreadListener {
        void onLoading();//刷新
    }
}
